﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;

namespace Elkomp {

	public partial class FormUploadNaSlika : Form {
		public string MainConnection;
		public string wherePart;

		public string ImageField { set; get; }

		public string UpdateTable { set; get; }

		public FormUploadNaSlika() {
			InitializeComponent();
		}

		private void btnExi_Click( object sender, EventArgs e ) {
			this.Close();
		}

		private void uploadFileToDatabase( byte[] picture, string fileName, string commandText ) {
			//
			// Defining the variables required for accesing the database server.
			//
			SqlConnection conn = null;
			SqlCommand cmd = null;
			SqlParameter pic = null;

			try {
				conn = new SqlConnection( MainConnection );
				cmd = new SqlCommand( commandText, conn );

				cmd.CommandType = System.Data.CommandType.Text;
				pic = new SqlParameter( "@Image", SqlDbType.Image );
				pic.Value = picture;

				cmd.Parameters.Add( pic );

				conn.Open();
				cmd.ExecuteNonQuery();
				conn.Close();

				conn.Dispose();
				cmd.Dispose();
			}
			catch ( Exception e ) {
				MessageBox.Show( e.Message );
			}
		}

		public void UploadFile( string FileName ) {
			if ( !File.Exists( FileName ) ) {
				MessageBox.Show( "Фајлот не постои" );
				return;
			}

			FileStream fs = null;
			try {
				#region Reading file

				fs = new FileStream( FileName, FileMode.Open );

				FileInfo fi = new FileInfo( FileName );
				long temp = fi.Length;
				int lung = Convert.ToInt32( temp );
				Progress.Maximum = lung;
				byte[] picture = new byte[lung];
				fs.Read( picture, 0, lung );
				fs.Close();

				#endregion Reading file

				Progress.Value = 0;
				for ( int i = 0; i < lung; i++ ) {
					Progress.Value += 1;
				}

				string UploadCommand = "Update " + UpdateTable + " Set " + ImageField + " = @Image " + wherePart;
				uploadFileToDatabase( picture, Pateka.Text, UploadCommand );
			}
			catch ( Exception e ) {
				Console.WriteLine( e.Message + " - " + e.StackTrace );
			}
		}

		private void btnOpen_Click( object sender, EventArgs e ) {
			OpenFileDialog dlgOpen = new OpenFileDialog();
			dlgOpen.Title = "Отвори слика";
			dlgOpen.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";
			dlgOpen.ShowDialog();
			if ( dlgOpen.FileName != "" ) {
				Pateka.Text = dlgOpen.FileName;
				if ( !Pateka.IsTextEmpty() ) {
					UploadFile( dlgOpen.FileName );
					while ( Progress.Value != Progress.Maximum ) { }
					this.Close();
				}
			}
		}
	}
}